<template>
  <div class="custom-tree-container">
    <div class="block">
      <!--      <p style="text-align: center">权限管理</p>-->
      <el-button
        type="primary"
        size="mini"
        style="margin-left: 20px"
        @click="editOrAdd = 1">
        添加权限
      </el-button>
      <el-button
        type="danger"
        size="mini"
        style="margin-left: 20px"
        @click="delChecked">
        删除选中
      </el-button>
      <el-tree
        :data="permissionsInfo"
        show-checkbox
        node-key="id"
        :load="loadNode"
        lazy
        :props="props"
        :expand-on-click-node="true"
        @check-change="handleCheckChange">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.perName }}</span>
        <span>
            <el-button
              v-if="data.parentId === -1"
              type="primary"
              size="mini"
              style="margin-right: 10px"
              @click.stop="() => append(node,data)">
            添加
          </el-button>
           <el-button
             v-if="data.parentId === -1"
             type="success"
             size="mini"
             @click.stop="() => edit(node,data)">
            编辑
          </el-button>
          <el-button
            v-else
            type="success"
            size="mini"
            @click.stop="() => edit(node,data)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click.stop="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
      </el-tree>
    </div>
    <el-dialog
      :title="editOrAdd === 1 ? '添加权限' : '修改权限'"
      @close="editOrAdd = 0"
      :visible="editOrAdd === 1 || editOrAdd === 2">
      <el-form :model="permissionInfoForm" :inline="true">
        <el-form-item label="权限名称" :label-width="formLabelWidth">
          <el-input style="width: auto;" maxlength="10" show-word-limit v-model="permissionInfoForm.perName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限代码" :label-width="formLabelWidth">
          <el-input style="width: auto;" maxlength="30" show-word-limit v-model="permissionInfoForm.perCode"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="editOrAdd === 2" label="更新时间" :label-width="formLabelWidth">
          <el-input style="width: auto;" disabled show-word-limit v-model="permissionInfoForm.updateTime"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="editOrAdd === 2" label="创建时间" :label-width="formLabelWidth">
          <el-input style="width: auto;" disabled show-word-limit v-model="permissionInfoForm.createTime"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" :label-width="formLabelWidth">
          <el-radio-group v-model="permissionInfoForm.isDisable">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <br>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editOrAdd = 0">取 消</el-button>
        <el-button
          v-if="editOrAdd === 1"
          type="primary"
          @click="addPermission">添加
        </el-button>
        <el-button
          v-else-if="editOrAdd === 2"
          type="primary"
          @click="updatePermission">确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getAllPermission, delPermission, updatePermission, addPermission } from '@/api/admin/permission/permissionManage'

  export default {
    data() {
      const permissionsInfo = []
      const props = {
        isLeaf: 'leaf',
        label: 'perName'
      }
      return {
        permissionsInfo: JSON.parse(JSON.stringify(permissionsInfo)),
        props,
        ids: [],
        editOrAdd: 0,//0：关闭，1：添加，2编辑
        formLabelWidth: '120px',
        permissionInfoForm: {},
        node: {}
      }
    },
    methods: {
      loadNode(node, resolve) {
        console.info(node)
        if (node.level === 0) {
          return this.getPermissions(-1)
        }
        if (node.data.parentId === -1) {
          this.getPermissions(node.data.id, resolve)
        }
      },
      append(node, data) {
        console.info(node)
        this.editOrAdd = 1
        this.permissionInfoForm.parentId = data.id
        // this.permissionInfoForm.node = node
        this.node = node
        console.info(data)
        //TODO
        // const newChild = { id: id++, label: 'testtest', children: [] }
        // if (!data.children) {
        //   this.$set(data, 'children', [])
        // }
        // data.children.push(newChild)
      },
      edit(node, data) {
        this.editOrAdd = 2
        this.permissionInfoForm = {
          'id': data.id,
          'isDisable': data.isDisable,
          'perCode': data.perCode,
          'perDes': data.perDes,
          'perHref': data.perHref,
          'perName': data.perName,
          'createTime': data.createTime,
          'updateTime': data.updateTime
        }
        this.permissionInfoForm.isDisable = this.permissionInfoForm.isDisable === 0 ? '0' : '1'
        this.node = node
      },
      remove(node, data) {
        const parent = node.parent
        const reqData = { ids: [data.id] }
        delPermission(reqData).then(response => {
          //刷新局部页面
          if (data.parentId === -1) {
            this.getPermissions(-1)
          } else {
            parent.loaded = false
            parent.expand()
          }
        }).catch(error => {
          console.info(error)
        })
      },
      delChecked() {
        // let ids = ''
        // this.ids.forEach(id => {
        //   ids += id + ','
        // })
        if (this.ids.length === 0) {
          alert('请先勾选！')
          return
        }
        let flag = confirm('注：只会清空子权限')
        if (!flag) return
        const reqData = { ids: this.ids }
        console.info(reqData)
        delPermission(reqData).then(response => {
          // this.$router.go(0)
          this.getPermissions(-1)
        }).catch(error => {
          console.info(error)
        })
      },
      handleCheckChange(data, checked, indeterminate) {
        // if (data.parentId === -1) {
        //   return
        // }
        let index = this.ids.findIndex(d => d === data.id)
        if (checked) {
          if (index === -1) {
            this.ids.push(data.id)
          }
        } else {
          if (index !== -1) {
            this.ids.splice(index, 1)
          }
        }
        console.info(this.ids)
      },
      getPermissions(parentId, resolve) {
        getAllPermission(parentId).then(response => {
          console.info(response)
          const resData = response.data
          if (parentId === -1) {
            this.permissionsInfo = []
          } else {
            this.permissionsInfo.forEach(item => {
              if (item.id === parentId) {
                item.children = []
              }
            })
          }
          resData.forEach((item) => {
            const updateTime = this.$moment(item.updateTime).format('YYYY-MM-DD hh:mm:ss')
            const createTime = this.$moment(item.createTime).format('YYYY-MM-DD hh:mm:ss')
            const permissionInfo = {
              id: item.id,
              isDelete: item.isDelete,
              isDisable: item.isDisable,
              perCode: item.perCode,
              perDes: item.perDes,
              perHref: item.perHref,
              parentId: item.parentId,
              perName: item.perName,
              updateTime: updateTime,
              createTime: createTime,
              children: []
            }
            if (parentId === -1) {
              this.permissionsInfo.push(permissionInfo)
            } else {
              permissionInfo['leaf'] = true
              this.permissionsInfo.forEach(per => {
                if (per.id === parentId) {
                  per.children.push(permissionInfo)
                }
              })
            }
          })
          resolve([])
        }).catch(error => {
          console.info(error)
        })
      },
      updatePermission() {
        const reqBody = {
          'is_disable': parseInt(this.permissionInfoForm.isDisable),
          'per_code': this.permissionInfoForm.perCode,
          'per_des': this.permissionInfoForm.perDes,
          'per_href': this.permissionInfoForm.perHref,
          'per_name': this.permissionInfoForm.perName
        }
        updatePermission(reqBody, this.permissionInfoForm.id).then(response => {
          console.info(response)
          this.editOrAdd = 0
          this.$message.success('修改成功')
          if (this.permissionInfoForm.parentId === -1) {
            this.getPermissions(-1)
          } else {
            this.node.parent.loaded = false
            this.node.parent.expand()
          }
        }).catch(error => {
          console.info(error)
        })
      },
      addPermission() {
        let reqData = this.permissionInfoForm
        reqData.isDisable = reqData.isDisable === '0' ? 0 : 1
        reqData.perDes = ''
        console.info(reqData)
        addPermission(reqData).then(response => {
          console.info(response)
          if (response.flag) {
            this.editOrAdd = 0
            if (reqData.parentId === -1) {
              // this.$message.success('添加成功,刷新页面可见!')
              // this.$router.go(0)
              this.getPermissions(-1)
            } else {
              this.node.loaded = false
              this.node.expand()
            }
          } else {
            this.$message.success('添加失败')
          }
        }).catch(error => {
          console.info(error)
        })
      },
      initPermissionInfoForm() {
        this.permissionInfoForm = {
          isDisable: '0',
          parentId: -1
        }
      }
    },
    watch: {
      editOrAdd: {
        handler(n, o) {
          console.info(n, o)
          if (n === 0) {
            this.initPermissionInfoForm()
            this.node = {}
          }
        }
      }
    },
    mounted() {
      this.initPermissionInfoForm()
    }
  }
</script>

<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .el-tree-node__content {
    margin-top: 10px;
    height: 40px;
  }
</style>
